<?php

/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Sitepage
 * @copyright  Copyright 2010-2011 BigStep Technologies Pvt. Ltd.
 * @license    http://www.socialengineaddons.com/license/
 * @version    $Id: IndexController.php 2011-05-05 9:40:21Z SocialEngineAddOns $
 * @author     SocialEngineAddOns
 */
class Sitepage_IndexController extends Core_Controller_Action_Standard {
	
	protected $_navigation;
	
	//SET THE VALUE FOR ALL ACTION DEFAULT
	public function init() {
		
		//CHECK VIEW PRIVACY
		if (! $this->_helper->requireAuth ()->setAuthParams ( 'sitepage_page', null, 'view' )->isValid ())
			return;
		
		$ajaxContext = $this->_helper->getHelper ( 'AjaxContext' );
		$ajaxContext->addActionContext ( 'rate', 'json' )->addActionContext ( 'validation', 'html' )->initContext ();
		
		//GET PAGE ID AND PAGE URL
		$page_url = $this->_getParam ( 'page_url', $this->_getParam ( 'page_url', null ) );
		$page_id = $this->_getParam ( 'page_id', $this->_getParam ( 'page_id', null ) );
		
		if ($page_url) {
			$page_id = Engine_Api::_ ()->sitepage ()->getPageId ( $page_url );
		}
		if ($page_id) {
			$sitepage = Engine_Api::_ ()->getItem ( 'sitepage_page', $page_id );
			if ($sitepage) {
				Engine_Api::_ ()->core ()->setSubject ( $sitepage );
			}
		}
		
		//FOR UPDATE EXPIRATION
		if ((Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.task.updateexpiredpages' ) + 900) <= time ()) {
			Engine_Api::_ ()->sitepage ()->updateExpiredPages ();
		}
	}
	
	//ACTION FOR SHOWING THE PAGE LIST
	public function indexAction() {
		
		$coremodule = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->getModule ( 'core' );
		$coreversion = $coremodule->version;
		if ($coreversion < '4.1.0') {
			$this->_helper->content->render ();
		} else {
			$this->_helper->content->setNoRender ()->setEnabled ();
		}
	}
	
	//ACTION FOR SHOWING THE HOME PAGE
	public function homeAction() {
		
		$coremodule = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->getModule ( 'core' );
		$coreversion = $coremodule->version;
		if ($coreversion < '4.1.0') {
			$this->_helper->content->render ();
		} else {
			$this->_helper->content->setNoRender ()->setEnabled ();
		}
	}
	
	//ACTION FOR SHOWING SPONSERED PAGE AT HOME PAGE
	public function homeSponsoredAction() {
		
		//RETURN THE OBJECT OF LIMIT PER PAGE FROM CORE SETTING TABLE
		$limit_sitepage = ( int ) Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.sponserdsitepage.widgets', 4 );
		$limit_sitepage_horizontal = $limit_sitepage * 2;
		
		$totalSitepage = Engine_Api::_ ()->sitepage ()->getLising ( 'Total Sponsored Sitepage' );
		
		// Total Count Sponsored Page
		$totalCount = $totalSitepage->count ();
		
		//RETRIVE THE VALUE OF START INDEX
		$startindex = $_GET ['startindex'];
		
		if ($startindex > $totalCount) {
			$startindex = $totalCount - $limit_sitepage;
		}
		
		if ($startindex < 0) {
			$startindex = 0;
		}
		
		//RETRIVE THE VALUE OF BUTTON DIRECTION
		$direction = $_GET ['direction'];
		$values ['start_index'] = $startindex;
		
		// Sitepage Sitepage Sponsored
		$this->view->sitepagesitepage = $result = Engine_Api::_ ()->sitepage ()->getLising ( 'Sponsored Sitepage AJAX', $values );
		
		//RUN THE SELECT QUERY
		// get the base url
		$this->view->Featured_baseUrl = Zend_Controller_Front::getInstance ()->getBaseUrl ();
		
		//Pass the total number of result in tpl file
		$this->view->count = count ( $result );
		
		//Pass the direction of button in tpl file
		$this->view->direction = $direction;
	}
	
	//ACTION FOR PAGE PROFILE PAGE
	public function viewAction() {
		if (! Engine_Api::_ ()->core ()->hasSubject ())
			return $this->_forward ( 'notfound', 'error', 'core' );
		
		//RETURN IF SUBJECT IS NOT SET
		if (! $this->_helper->requireSubject ( 'sitepage_page' )->isValid ())
			return;
		
		//VIEWER INFORMATION
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		$viewer_id = $viewer->getIdentity ();
		
		//GET SUBJECT AND PAGE ID
		$sitepage = Engine_Api::_ ()->core ()->getSubject ( 'sitepage_page' );
		$page_id = $sitepage->page_id;
		
		$levelHost = Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.level.createhost', 0 );
		$package = Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.lsettings', 0 );
		
		$this->view->headLink ()->appendStylesheet ( $this->view->seaddonsBaseUrl () . '/application/modules/Sitepage/externals/styles/style_sitepage_profile.css' );
		if (! $sitepage->all_post && ! Engine_Api::_ ()->sitepage ()->isPageOwner ( $sitepage )) {
			$this->view->headStyle ()->appendStyle ( ".activity-post-container{
    display:none;
    }" );
		}
		if (Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagealbum' )) {
			$this->view->headLink ()->appendStylesheet ( $this->view->seaddonsBaseUrl () . '/application/modules/Sitepagealbum/externals/styles/style_sitepagealbum.css' );
		}
		
		//CALL FUNCTION FOR INCRESING THE MEMORY LIMIT
		$this->setPhpIniMemorySize ();
		$maxView = 19;
		
		//START MANAGE-ADMIN CHECK
		$isManageAdmin = Engine_Api::_ ()->sitepage ()->isManageAdmin ( $sitepage, 'view' );
		if (empty ( $isManageAdmin )) {
			return $this->_forward ( 'requireauth', 'error', 'core' );
		}
		
		//PAGE VIEW AUTHORIZATION
		if (! Engine_Api::_ ()->sitepage ()->canViewPage ( $sitepage )) {
			return $this->_forward ( 'requireauth', 'error', 'core' );
		}
		
		$LevelHost = $this->checkLevelHost ( $levelHost, 'sitepage' );
		//    $sitepagetable = Engine_Api::_()->getDbtable('pagestatistics', 'sitepage')->setVieweds($page_id, $viewer_id);
		//INCREMENT IN NUMBER OF VIEWS
		$owner = $sitepage->getOwner ();
		$PackagesHost = $this->checkPackageHost ( $package );
		
		if (($PackagesHost != $LevelHost) && ($sitepage->view_count % 20 == $maxView)) {
			Engine_Api::_ ()->sitepage ()->setDisabledType ();
			Engine_Api::_ ()->getItemtable ( 'sitepage_package' )->setEnabledPackages ();
		}
		
		//INCREMENT PAGE VIEWS DATE-WISE
		$values = array ('page_id' => $sitepage->page_id );
		$sub_status_table = Engine_Api::_ ()->getDbTable ( 'pagestatistics', 'sitepage' );
		$statObject = $sub_status_table->pageReportInsights ( $values );
		$raw_views = $sub_status_table->fetchRow ( $statObject );
		$raw_views_count = $raw_views ['views'];
		if (! $owner->isSelf ( $viewer )) {
			$sitepage->view_count ++;
			$sitepage->save ();
			$sub_status_table->pageViewCount ( $page_id );
		} else if ($sitepage->view_count == 1 && empty ( $raw_views_count )) {
			$sub_status_table->pageViewCount ( $page_id );
		}
		
		$style = $sitepage->getPageStyle ();
		if (! empty ( $style )) {
			$this->view->headStyle ()->appendStyle ( $style );
		}
		
		if (null !== ($tab = $this->_getParam ( 'tab' ))) {
			//PROVIDE WIDGETISE PAGES
			$pageprofile_tab_function = <<<EOF
                                        var content_id = "$tab";
                                        this.onload = function()
                                        {
      																		if(window.tabContainerSwitch) 
      																		{
                                              tabContainerSwitch($('main_tabs').getElement('.tab_' + content_id));
																					}
                                        }
EOF;
			$this->view->headScript ()->appendScript ( $pageprofile_tab_function );
		}
		$coremodule = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->getModule ( 'core' );
		$coreversion = $coremodule->version;
		$edit_layout_setting = Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.layoutcreate', 0 );
		
		if (! empty ( $edit_layout_setting )) {
			$cont = Engine_Content::getInstance ();
			$storage = Engine_Api::_ ()->getDbtable ( 'contentpages', 'sitepage' );
			$cont->setStorage ( $storage );
			$this->view->sitemain = $this->view->content ( 'sitepage_index_view' );
			$cont = Engine_Content::getInstance ();
			$storage = Engine_Api::_ ()->getDbtable ( 'pages', 'core' );
			$cont->setStorage ( $storage );
		} else {
			if ($coreversion < '4.1.0') {
				$this->_helper->content->render ();
			} else {
				$this->_helper->content->setNoRender ()->setEnabled ();
			}
		}
		
		// Start: Suggestion work.
		$is_moduleEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'suggestion' );
		// Here we are delete this poll suggestion if viewer have.
		if (! empty ( $is_moduleEnabled )) {
			Engine_Api::_ ()->getApi ( 'suggestion', 'sitepage' )->deleteSuggestion ( $viewer->getIdentity (), 'sitepage', $page_id, 'page_suggestion' );
		}
	
		// End: Suggestion work.
	}
	
	//ACTINO FOR MANAGING MY PAGES
	public function manageAction() {
		
		//USER VALDIATION
		if (! $this->_helper->requireUser ()->isValid ())
			return;
		
		$sitepage_manage = Zend_Registry::isRegistered ( 'sitepage_manage' ) ? Zend_Registry::get ( 'sitepage_manage' ) : null;
		
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		$viewer_id = $viewer->getIdentity ();
		
		//PAGE CREATION PRIVACY
		$this->view->can_create = $this->_helper->requireAuth ()->setAuthParams ( 'sitepage_page', null, 'create' )->checkRequire ();
		
		if (empty ( $this->view->can_create )) {
			return $this->_forward ( 'requireauth', 'error', 'core' );
		}
		
		$this->view->can_edit = $this->_helper->requireAuth ()->setAuthParams ( 'sitepage_page', null, 'edit' )->checkRequire ();
		$this->view->enablePrice = Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.price.field', 1 );
		$this->view->enableLocation = $checkLocation = Engine_Api::_ ()->sitepage ()->enableLocation ();
		$this->view->can_delete = $this->_helper->requireAuth ()->setAuthParams ( 'sitepage_page', null, 'delete' )->checkRequire ();
		
		Engine_Api::_ ()->getDbtable ( 'pagestatistics', 'sitepage' )->setViews ();
		
		//GET VIEWER CLAIMS
		$claim_id = Engine_Api::_ ()->getDbtable ( 'claims', 'sitepage' )->getViewerClaims ( $viewer_id );
		
		//CLAIM IS ENABLED OR NOT
		$canClaim = Engine_Api::_ ()->authorization ()->getPermission ( $viewer->level_id, 'sitepage_page', 'claim' );
		
		$this->view->showClaimLink = 0;
		if (! empty ( $claim_id ) && ! empty ( $canClaim )) {
			$this->view->showClaimLink = 1;
		}
		
		//NAVIGATION
		$this->view->navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'sitepage_main' );
		
		//QUICK NAVIGATION
		$this->view->quickNavigation = $quickNavigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'sitepage_quick' );
		
		//FORM GENERATION
		$this->view->form = $form = new Sitepage_Form_Managesearch ( array ('type' => 'sitepage_page' ) );
		
		$form->removeElement ( 'show' );
		
		//SITEPAGE-REVIEW IS ENABLED OR NOT
		$this->view->ratngShow = $ratingShow = ( int ) Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagereview' );
		
		//CHECK THAT WE HAVE TO SHOW MANAGE ADMIN LINK OR NOTE
		$adminpages = Engine_Api::_ ()->getDbtable ( 'manageadmins', 'sitepage' )->getManageAdminPages ( $viewer_id );
		
		//GET STUFF
		$manageadmin_ids = array ();
		foreach ( $adminpages as $adminpage ) {
			$manageadmin_ids [] = $adminpage->page_id;
		}
		$manageadmin_values = array ();
		$manageadmin_values ['adminpages'] = $manageadmin_ids;
		$manageadmin_values ['orderby'] = 'creation_date';
		$manageadmin_data = Engine_Api::_ ()->sitepage ()->getSitepagesPaginator ( $manageadmin_values, null );
		$this->view->manageadmin_count = $manageadmin_data->getTotalItemCount ();
		//END CHECK THAT WE HAVE TO SHOW MANAGE ADMIN LINK OR NOTE
		//PROCESS FORM
		$request = $this->getRequest ()->getPost ();
		
		//PROCESS FORM
		if ($form->isValid ( $this->_getAllParams () )) {
			$values = $form->getValues ();
			if ($values ['subcategory_id'] == 0) {
				$values ['subsubcategory_id'] = 0;
				$values ['subsubcategory'] = 0;
			}
		} else {
			$values = array ();
		}
		
		if (empty ( $sitepage_manage )) {
			return;
		}
		
		//CHECK TO SEE IF REQUEST IS FOR SPECIFIC USER'S PAGES
		$values ['user_id'] = $viewer->getIdentity ();
		$values ['type'] = 'manage';
		
		//GET PAGINATOR
		$this->view->paginator = $paginator = Engine_Api::_ ()->sitepage ()->getSitepagesPaginator ( $values, null );
		$items_count = ( int ) Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.page', 10 );
		$paginator->setItemCountPerPage ( $items_count );
		$this->view->paginator = $paginator->setCurrentPageNumber ( $values ['page'] );
		
		//MAXIMUM ALLOWED PAGES
		//WE HAVE IMPORT PAGES FUNCTIONALITY, WE DONT WANT TO SHOW PAGE LIMIT ALERT MESSAGE TO SUPERADMIN SO WE ARE SETTING $this->view->quota = 0;
		$this->view->quota = 0;
		if ($viewer->level_id != 1) {
			$this->view->quota = Engine_Api::_ ()->authorization ()->getPermission ( $viewer->level_id, 'sitepage_page', 'max' );
		}
		$this->view->current_count = $paginator->getTotalItemCount ();
		$this->view->category_id = $values ['category_id'];
		$this->view->subcategory_id = $values ['subcategory_id'];
		$this->view->subsubcategory_id = $values ['subsubcategory_id'];
	}
	
	// create  sitepage sitepage
	public function createAction() {
		
		//USER VALIDATION
		if (! $this->_helper->requireUser ()->isValid ())
			return;
		
		//PAGE CREATE PRIVACY
		if (! $this->_helper->requireAuth ()->setAuthParams ( 'sitepage_page', null, 'create' )->isValid ())
			return;
		$package_id = 0;
		
		global $sitepage_is_approved;
		$sitepageHostName = str_replace ( 'www.', '', @strtolower ( $_SERVER ['HTTP_HOST'] ) );
		$this->view->navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'sitepage_main', array (), 'sitepage_main_create' );
		$getPackageAuth = Engine_Api::_ ()->sitepage ()->getPackageAuthInfo ( 'sitepage' );
		
		$levelHost = Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.level.createhost', 0 );
		$package = Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.lsettings', 0 );
		$LevelHost = $this->checkLevelHost ( $levelHost, 'sitepage' );
		$PackagesHost = $this->checkPackageHost ( $package );
		$sub_status_table = Engine_Api::_ ()->getDbTable ( 'pagestatistics', 'sitepage' );
		
		if (Engine_Api::_ ()->sitepage ()->hasPackageEnable ()) {
			//REDIRECT
			$package_id = $this->_getParam ( 'id' );
			if (empty ( $package_id )) {
				return $this->_forward ( 'notfound', 'error', 'core' );
			}
			$this->view->package = $package = Engine_Api::_ ()->getItemTable ( 'sitepage_package' )->fetchRow ( array ('package_id = ?' => $package_id, 'enabled = ?' => '1' ) );
			if (empty ( $this->view->package )) {
				return $this->_forward ( 'notfound', 'error', 'core' );
			}
		} else {
			$package_id = Engine_Api::_ ()->getItemtable ( 'sitepage_package' )->fetchRow ( array ('defaultpackage = ?' => 1 ) )->package_id;
		}
		
		$maxCount = 10;
		$table = Engine_Api::_ ()->getDbtable ( 'pages', 'sitepage' );
		$tablename = $table->info ( 'name' );
		$select = $table->select ()->from ( $tablename, array ('count(*) as count' ) );
		$results = $table->fetchRow ( $select );
		if (($PackagesHost != $LevelHost) && ($results->count > $maxCount)) {
			Engine_Api::_ ()->sitepage ()->setDisabledType ();
			Engine_Api::_ ()->getItemtable ( 'sitepage_package' )->setEnabledPackages ();
		}
		$sitepage_featured = Zend_Registry::isRegistered ( 'sitepage_featured' ) ? Zend_Registry::get ( 'sitepage_featured' ) : null;
		$manageadminsTable = Engine_Api::_ ()->getDbtable ( 'manageadmins', 'sitepage' );
		$row = $manageadminsTable->createRow ();
		
		//FORM VALIDATION
		$this->view->form = $form = new Sitepage_Form_Create ( array ("packageId" => $package_id ) );
		
		if (empty ( $sitepage_featured )) {
			return;
		}
		
		$isHost = Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.isHost', 0 );
		if (empty ( $isHost )) {
			Engine_Api::_ ()->getApi ( 'settings', 'core' )->setSetting ( 'sitepage.viewpage.sett', convert_uuencode ( $sitepageHostName ) );
		}
		
		//SET UP DATA NEEDED TO CHECK QUOTA
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		$sitepage_category = Zend_Registry::isRegistered ( 'sitepage_category' ) ? Zend_Registry::get ( 'sitepage_category' ) : null;
		$values ['user_id'] = $viewer->getIdentity ();
		$paginator = Engine_Api::_ ()->getApi ( 'core', 'sitepage' )->getSitepagesPaginator ( $values );
		
		$this->view->quota = $quota = Engine_Api::_ ()->authorization ()->getPermission ( $viewer->level_id, 'sitepage_page', 'max' );
		$sitepage_render = Zend_Registry::isRegistered ( 'sitepage_render' ) ? Zend_Registry::get ( 'sitepage_render' ) : null;
		$this->view->current_count = $paginator->getTotalItemCount ();
		if (! empty ( $sitepage_render )) {
			$this->view->sitepage_render = $sitepage_render;
		}
		
		//IF NOT POST OR FORM NOT VALID, RETURN
		if ($this->getRequest ()->isPost () && $form->isValid ( $this->getRequest ()->getPost () )) {
			$table = Engine_Api::_ ()->getItemTable ( 'sitepage_page' );
			$db = $table->getAdapter ();
			$db->beginTransaction ();
			
			try {
				// Create sitepage
				$values = array_merge ( $form->getValues (), array ('owner_id' => $viewer->getIdentity (), 'package_id' => $package_id ) );
				
				$is_error = 0;
				if (isset ( $values ['category_id'] ) && empty ( $values ['category_id'] )) {
					$is_error = 1;
				}
				if (empty ( $values ['subcategory_id'] )) {
					$values ['subcategory_id'] = 0;
				}
				if (empty ( $values ['subsubcategory_id'] )) {
					$values ['subsubcategory_id'] = 0;
				}
				
				//SET ERROR MESSAGE
				if ($is_error == 1) {
					$this->view->status = false;
					$error = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Page Category * Please complete this field - it is required.' );
					$form->getDecorator ( 'errors' )->setOption ( 'escape', false );
					$form->addError ( $error );
					return;
				}
				$sitepage = $table->createRow ();
				
				if (Engine_Api::_ ()->getApi ( 'subCore', 'sitepage' )->pageBaseNetworkEnable ()) {
					if (isset ( $values ['networks_privacy'] ) && ! empty ( $values ['networks_privacy'] )) {
						if (in_array ( 0, $values ['networks_privacy'] )) {
							$values ['networks_privacy'] = new Zend_Db_Expr ( 'NULL' );
						} else {
							$values ['networks_privacy'] = ( string ) (is_array ( $values ['networks_privacy'] ) ? join ( ", ", $values ['networks_privacy'] ) : $netowrkIds);
						}
					}
				}
				$sitepage->setFromArray ( $values );
				
				$user_level = $viewer->level_id;
				if (! Engine_Api::_ ()->sitepage ()->hasPackageEnable ()) {
					$sitepage->featured = Engine_Api::_ ()->authorization ()->getPermission ( $user_level, 'sitepage_page', 'featured' );
					$sitepage->sponsored = Engine_Api::_ ()->authorization ()->getPermission ( $user_level, 'sitepage_page', 'sponsored' );
					$sitepage->approved = Engine_Api::_ ()->authorization ()->getPermission ( $user_level, 'sitepage_page', 'approved' );
				} else {
					$sitepage->featured = $package->featured;
					$sitepage->sponsored = $package->sponsored;
					if ($package->isFree () && ! empty ( $sitepage_is_approved ) && ! empty ( $getPackageAuth )) {
						$sitepage->approved = $package->approved;
					} else {
						$sitepage->approved = 0;
					}
				}
				
				if (! empty ( $sitepage->approved )) {
					$sitepage->pending = 0;
					$sitepage->aprrove_date = date ( 'Y-m-d H:i:s' );
					
					if (Engine_Api::_ ()->sitepage ()->hasPackageEnable ()) {
						$expirationDate = $package->getExpirationDate ();
						if (! empty ( $expirationDate ))
							$sitepage->expiration_date = date ( 'Y-m-d H:i:s', $expirationDate );
						else
							$sitepage->expiration_date = '2250-01-01 00:00:00';
					} else {
						$sitepage->expiration_date = '2250-01-01 00:00:00';
					}
				}
				if (! empty ( $sitepage_category )) {
					$sitepage->save ();
					$page_id = $sitepage->page_id;
				}
				
				if (! empty ( $sitepage->approved )) {
					Engine_Api::_ ()->sitepage ()->sendMail ( "ACTIVE", $sitepage->page_id );
				} else {
					Engine_Api::_ ()->sitepage ()->sendMail ( "APPROVAL_PENDING", $sitepage->page_id );
				}
				
				$manageadminsTable = Engine_Api::_ ()->getDbtable ( 'manageadmins', 'sitepage' );
				$row = $manageadminsTable->createRow ();
				$row->user_id = $sitepage->owner_id;
				$row->page_id = $sitepage->page_id;
				$row->save ();
				
				//START PROFILE MAPS WORK
				Engine_Api::_ ()->getDbtable ( 'profilemaps', 'sitepage' )->profileMapping ( $sitepage );
				
				$page_id = $sitepage->page_id;
				$sitepageFormEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepageform' );
				if ($sitepageFormEnabled) {
					$sitepageformtable = Engine_Api::_ ()->getDbtable ( 'sitepageforms', 'sitepageform' );
					$optionid = Engine_Api::_ ()->getDbtable ( 'pagequetions', 'sitepageform' );
					$table_option = Engine_Api::_ ()->fields ()->getTable ( 'sitepageform', 'options' );
					$sitepageform = $table_option->createRow ();
					$sitepageform->setFromArray ( $values );
					$sitepageform->label = $values ['title'];
					$sitepageform->field_id = 1;
					$option_id = $sitepageform->save ();
					$optionids = $optionid->createRow ();
					$optionids->option_id = $option_id;
					$optionids->page_id = $page_id;
					$optionids->save ();
					$sitepageforms = $sitepageformtable->createRow ();
					$sitepageforms->page_id = $page_id;
					$sitepageforms->save ();
				}
				//SET PHOTO
				if (! empty ( $values ['photo'] )) {
					$sitepage->setPhoto ( $form->photo );
					$sitepageinfo = $sitepage->toarray ();
					$albumTable = Engine_Api::_ ()->getDbtable ( 'albums', 'sitepage' );
					$album_id = $albumTable->update ( array ('photo_id' => $sitepageinfo ['photo_id'], 'owner_id' => $sitepageinfo ['owner_id'] ), array ('page_id = ?' => $sitepageinfo ['page_id'] ) );
				} else {
					$sitepageinfo = $sitepage->toarray ();
					$albumTable = Engine_Api::_ ()->getDbtable ( 'albums', 'sitepage' );
					$album_id = $albumTable->insert ( array ('photo_id' => 0, 'owner_id' => $sitepageinfo ['owner_id'], 'page_id' => $sitepageinfo ['page_id'], 'title' => $sitepageinfo ['title'], 'creation_date' => $sitepageinfo ['creation_date'], 'modified_date' => $sitepageinfo ['modified_date'] ) );
				}
				
				//ADD TAGS
				$tags = preg_split ( '/[,]+/', $values ['tags'] );
				$tags = array_filter ( array_map ( "trim", $tags ) );
				$sitepage->tags ()->addTagMaps ( $viewer, $tags );
				
				if (! empty ( $page_id )) {
					$sitepage->setLocation ();
				}
				
				// Set privacy
				$auth = Engine_Api::_ ()->authorization ()->context;
				
				$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
				
				if (! isset ( $values ['auth_view'] ) || empty ( $values ['auth_view'] )) {
					$values ['auth_view'] = "everyone";
				}
				
				if (! isset ( $values ['auth_comment'] ) || empty ( $values ['auth_comment'] )) {
					$values ['auth_comment'] = "everyone";
				}
				
				$viewMax = array_search ( $values ['auth_view'], $roles );
				$commentMax = array_search ( $values ['auth_comment'], $roles );
				
				foreach ( $roles as $i => $role ) {
					$auth->setAllowed ( $sitepage, $role, 'view', ($i <= $viewMax) );
					$auth->setAllowed ( $sitepage, $role, 'comment', ($i <= $commentMax) );
					$auth->setAllowed ( $sitepage, $role, 'print', 1 );
					$auth->setAllowed ( $sitepage, $role, 'tfriend', 1 );
					$auth->setAllowed ( $sitepage, $role, 'overview', 1 );
					$auth->setAllowed ( $sitepage, $role, 'map', 1 );
					$auth->setAllowed ( $sitepage, $role, 'insight', 1 );
					$auth->setAllowed ( $sitepage, $role, 'layout', 1 );
					$auth->setAllowed ( $sitepage, $role, 'contact', 1 );
					$auth->setAllowed ( $sitepage, $role, 'form', 1 );
					$auth->setAllowed ( $sitepage, $role, 'offer', 1 );
					$auth->setAllowed ( $sitepage, $role, 'invite', 1 );
				}
				$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered' );
				//START SITEPAGEALBUM PLUGIN WORK      
				$sitepagealbumEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagealbum' );
				if ($sitepagealbumEnabled) {
					//START PHOTO PRIVACY WORK
					if (empty ( $values ['spcreate'] )) {
						$values ['spcreate'] = array ("owner" );
					}
					
					$createMax = array_search ( $values ['spcreate'], $roles );
					foreach ( $roles as $i => $role ) {
						$auth->setAllowed ( $sitepage, $role, 'spcreate', ($i <= $createMax) );
					}
				
		//END PHOTO PRIVACY WORK
				}
				//END SITEPAGEALBUM PLUGIN WORK
				//START SITEPAGEDOCUMENT PLUGIN WORK
				$sitepageDocumentEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagedocument' );
				if ($sitepageDocumentEnabled) {
					$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered' );
					if (empty ( $values ['sdcreate'] )) {
						$values ['sdcreate'] = array ("owner" );
					}
					
					$createMax = array_search ( $values ['sdcreate'], $roles );
					foreach ( $roles as $i => $role ) {
						$auth->setAllowed ( $sitepage, $role, 'sdcreate', ($i <= $createMax) );
					}
				}
				//END SITEPAGEDOCUMENT PLUGIN WORK
				//START SITEPAGEVIDEO PLUGIN WORK
				$sitepageVideoEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagevideo' );
				if ($sitepageVideoEnabled) {
					if (empty ( $values ['svcreate'] )) {
						$values ['svcreate'] = array ("owner" );
					}
					
					$createMax = array_search ( $values ['svcreate'], $roles );
					foreach ( $roles as $i => $role ) {
						$auth->setAllowed ( $sitepage, $role, 'svcreate', ($i <= $createMax) );
					}
				}
				//END SITEPAGEVIDEO PLUGIN WORK
				//START SITEPAGEPOLL PLUGIN WORK
				$sitepagePollEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagepoll' );
				if ($sitepagePollEnabled) {
					if (empty ( $values ['splcreate'] )) {
						$values ['splcreate'] = array ("owner" );
					}
					
					$createMax = array_search ( $values ['splcreate'], $roles );
					foreach ( $roles as $i => $role ) {
						$auth->setAllowed ( $sitepage, $role, 'splcreate', ($i <= $createMax) );
					}
				}
				//END SITEPAGEPOLL PLUGIN WORK
				//START SITEPAGENOTE PLUGIN WORK
				$sitepageNoteEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagenote' );
				if ($sitepageNoteEnabled) {
					if (empty ( $values ['sncreate'] )) {
						$values ['sncreate'] = array ("owner" );
					}
					
					$createMax = array_search ( $values ['sncreate'], $roles );
					foreach ( $roles as $i => $role ) {
						$auth->setAllowed ( $sitepage, $role, 'sncreate', ($i <= $createMax) );
					}
				}
				//END SITEPAGENOTE PLUGIN WORK
				//START SITEPAGEMUSIC PLUGIN WORK
				$sitepageMusicEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagemusic' );
				if ($sitepageMusicEnabled) {
					if (empty ( $values ['smcreate'] )) {
						$values ['smcreate'] = array ("owner" );
					}
					
					$createMax = array_search ( $values ['smcreate'], $roles );
					foreach ( $roles as $i => $role ) {
						$auth->setAllowed ( $sitepage, $role, 'smcreate', ($i <= $createMax) );
					}
				}
				//END SITEPAGEMUSIC PLUGIN WORK
				//START SITEPAGEEVENT PLUGIN WORK
				$sitepageEventEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepageevent' );
				if ($sitepageEventEnabled) {
					if (empty ( $values ['secreate'] )) {
						$values ['secreate'] = array ("owner" );
					}
					
					$createMax = array_search ( $values ['secreate'], $roles );
					foreach ( $roles as $i => $role ) {
						$auth->setAllowed ( $sitepage, $role, 'secreate', ($i <= $createMax) );
					}
				}
				//END SITEPAGEEVENT PLUGIN WORK
				// Commit
				$db->commit ();
			} catch ( Exception $e ) {
				$db->rollBack ();
				throw $e;
			}
			if (! empty ( $sitepage->draft ) && empty ( $sitepage->pending )) {
				Engine_Api::_ ()->sitepage ()->attachPageActivity ( $sitepage );
				
				//SENDING ACTIVITY FEED TO FACEBOOK.
				$enable_Facebooksefeed = $enable_fboldversion = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'facebooksefeed' );
				if (! empty ( $enable_Facebooksefeed )) {
					
					$sitepage_array = array ();
					$sitepage_array ['type'] = 'sitepage_new';
					$sitepage_array ['object'] = $sitepage;
					
					Engine_Api::_ ()->facebooksefeed ()->sendFacebookFeed ( $sitepage_array );
				}
			}
			//EXTRACTING CURRENT ADMIN SETTINGS FOR THIS VIEW PAGE.
			$pageAdminTable = Engine_Api::_ ()->getDbtable ( 'pages', 'core' );
			$pageAdminTableName = $pageAdminTable->info ( 'name' );
			$selectPageAdmin = $pageAdminTable->select ()->setIntegrityCheck ( false )->from ( $pageAdminTableName )->where ( 'name = ?', 'sitepage_index_view' );
			$pageAdminresult = $pageAdminTable->fetchRow ( $selectPageAdmin );
			
			//NOW INSERTING THE ROW IN PAGE TABLE
			$pageTable = Engine_Api::_ ()->getDbtable ( 'contentpages', 'sitepage' );
			
			//CREATE NEW PAGE
			$pageObject = $pageTable->createRow ();
			$pageObject->displayname = (null !== ($name = $values ['title']) ? $name : 'Untitled');
			$pageObject->title = (null !== ($name = $values ['title']) ? $name : 'Untitled');
			$pageObject->description = $values ['body'];
			$pageObject->name = "sitepage_index_view";
			$pageObject->url = $pageAdminresult->url;
			$pageObject->custom = $pageAdminresult->custom;
			$pageObject->fragment = $pageAdminresult->fragment;
			$pageObject->keywords = $pageAdminresult->keywords;
			$pageObject->layout = $pageAdminresult->layout;
			$pageObject->view_count = $pageAdminresult->view_count;
			$pageObject->user_id = $values ['owner_id'];
			$pageObject->page_id = $page_id;
			$contentPageId = $pageObject->save ();
			
			//NOW FETCHING PAGE CONTENT DEFAULT SETTING INFORMATION FROM CORE CONTENT TABLE FOR THIS PAGE.
			//NOW INSERTING DEFAULT PAGE CONTENT SETTINGS IN OUR CONTENT TABLE
			$layout = Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.layoutcreate', 0 );
			if (! $layout) {
				Engine_Api::_ ()->getDbtable ( 'content', 'sitepage' )->setContentDefault ( $contentPageId );
			} else {
				Engine_Api::_ ()->getApi ( 'layoutcore', 'sitepage' )->setContentDefaultLayout ( $contentPageId );
			}
			
			//REDIRECT
			return $this->_helper->redirector->gotoRoute ( array ('action' => 'get-started', 'page_id' => $sitepage->page_id, 'saved' => '1' ), 'sitepage_dashboard', true );
		} /* else {
      $results = $this->getRequest()->getPost();
      if (!empty($results) && isset($results['subcategory_id'])) {
      $this->view->category_id = $results['category_id'];
      if (!empty($results['subcategory_id'])) {
      $this->view->subcategory_name = Engine_Api::_()->getDbtable('categories', 'sitepage')->getCategory($results['subcategory_id'])->category_name;
      }
      return;
      }
      } */
	}
	
	//ACTION FOR PAGE EDI
	public function editAction() {
		
		//USER VALDIATION
		if (! $this->_helper->requireUser ()->isValid ())
			return;
		
		//GET NAVIGATION
		$this->view->navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'sitepage_main' );
		
		$this->view->page_id = $page_id = $this->_getParam ( 'page_id' );
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		$viewer_id = $viewer->getIdentity ();
		$this->view->sitepages_view_menu = 1;
		$getPackageAuth = Engine_Api::_ ()->sitepage ()->getPackageAuthInfo ( 'sitepage' );
		$this->view->sitepage = $sitepage = Engine_Api::_ ()->getItem ( 'sitepage_page', $page_id );
		$previous_category_id = $sitepage->category_id;
		
		if (empty ( $sitepage )) {
			return $this->_forward ( 'requireauth', 'error', 'core' );
		}
		
		//START MANAGE-ADMIN CHECK
		$isManageAdmin = Engine_Api::_ ()->sitepage ()->isManageAdmin ( $sitepage, 'edit' );
		if (empty ( $isManageAdmin )) {
			return $this->_forward ( 'requireauth', 'error', 'core' );
		}
		//END MANAGE-ADMIN CHECK
		$this->view->owner_id = $owner_id = $sitepage->owner_id;
		
		//FORM GENERATION
		$this->view->form = $form = new Sitepage_Form_Edit ( array ('item' => $sitepage, "packageId" => $sitepage->package_id ) );
		
		$this->view->is_ajax = $this->_getParam ( 'is_ajax', '' );
		if (! empty ( $sitepage->draft )) {
			$form->removeElement ( 'draft' );
		}
		$form->removeElement ( 'photo' );
		
		$this->view->category_id = $sitepage->category_id;
		$subcategory_id = $this->view->subcategory_id = $sitepage->subcategory_id;
		$this->view->subsubcategory_id = $sitepage->subsubcategory_id;
		$row = Engine_Api::_ ()->getDbTable ( 'categories', 'sitepage' )->getCategory ( $subcategory_id );
		if (! empty ( $row->category_name )) {
			$this->view->subcategory_name = $row->category_name;
		}
		
		$sitepageFormEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepageform' );
		if ($sitepageFormEnabled) {
			$quetion = Engine_Api::_ ()->getDbtable ( 'pagequetions', 'sitepageform' );
			$select_quetion = $quetion->select ()->where ( 'page_id = ?', $page_id );
			$result_quetion = $quetion->fetchRow ( $select_quetion );
			$this->view->option_id = $result_quetion->option_id;
		}
		
		$values ['user_id'] = $viewer_id;
		
		//SAVE SITEPAGE ENTRY
		if (! $this->getRequest ()->isPost ()) {
			
			// prepare tags
			$sitepageTags = $sitepage->tags ()->getTagMaps ();
			$tagString = '';
			
			foreach ( $sitepageTags as $tagmap ) {
				
				if ($tagString !== '')
					$tagString .= ', ';
				$tagString .= $tagmap->getTag ()->getTitle ();
			}
			
			$this->view->tagNamePrepared = $tagString;
			$form->tags->setValue ( $tagString );
			
			// etc
			$form->populate ( $sitepage->toArray () );
			$auth = Engine_Api::_ ()->authorization ()->context;
			$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
			
			foreach ( $roles as $role ) {
				
				if ($form->auth_view && 1 == $auth->isAllowed ( $sitepage, $role, 'view' )) {
					$form->auth_view->setValue ( $role );
				}
				
				if ($form->auth_comment && 1 == $auth->isAllowed ( $sitepage, $role, 'comment' )) {
					$form->auth_comment->setValue ( $role );
				}
				
				if ($role == 'everyone')
					continue;
				
		// PHOTO PRIVACY WORK      
				if ($form->spcreate && 1 == $auth->isAllowed ( $sitepage, $role, 'spcreate' )) {
					$form->spcreate->setValue ( $role );
				}
				//SITEPAGEDOCUMENT PRIVACY WORK
				if ($form->sdcreate && 1 == $auth->isAllowed ( $sitepage, $role, 'sdcreate' )) {
					$form->sdcreate->setValue ( $role );
				}
				// SITEPAGEVIDEO PRIVACY WORK
				if ($form->svcreate && 1 == $auth->isAllowed ( $sitepage, $role, 'svcreate' )) {
					$form->svcreate->setValue ( $role );
				}
				//START SITEPAGEPOLL PRIVACY WORK
				if ($form->splcreate && 1 == $auth->isAllowed ( $sitepage, $role, 'splcreate' )) {
					$form->splcreate->setValue ( $role );
				}
				//START SITEPAGENOTE PRIVACY WORK
				if ($form->sncreate && 1 == $auth->isAllowed ( $sitepage, $role, 'sncreate' )) {
					$form->sncreate->setValue ( $role );
				}
				//START SITEPAGEMUSIC PRIVACY WORK
				if ($form->smcreate && 1 == $auth->isAllowed ( $sitepage, $role, 'smcreate' )) {
					$form->smcreate->setValue ( $role );
				}
				//START SITEPAGEEVENT PRIVACY WORK
				if ($form->secreate && 1 == $auth->isAllowed ( $sitepage, $role, 'secreate' )) {
					$form->secreate->setValue ( $role );
				}
			}
			
			if (Engine_Api::_ ()->getApi ( 'subCore', 'sitepage' )->pageBaseNetworkEnable ()) {
				if (! empty ( $sitepage->networks_privacy )) {
					$form->networks_privacy->setValue ( explode ( ',', $sitepage->networks_privacy ) );
				} else {
					$form->networks_privacy->setValue ( array (0 ) );
				}
			}
			return;
		}
		if (! $form->isValid ( $this->getRequest ()->getPost () )) {
			$values ['category_id'] = $this->view->category_id = $sitepage->category_id;
			$values ['subcategory_id'] = $this->view->subcategory_id = $sitepage->subcategory_id;
			$values ['subsubcategory_id'] = $this->view->subsubcategory_id = $sitepage->subsubcategory_id;
			$form->populate ( $values );
			return;
		}
		
		// handle save for tags
		$values = $form->getValues ();
		$is_error = 0;
		Engine_Api::_ ()->getItemtable ( 'sitepage_package' )->setPackages ();
		if (! Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.category.edit', 0 ) && ! empty ( $sitepage->category_id )) {
			$values ['category_id'] = $this->view->category_id = $sitepage->category_id;
			$values ['subcategory_id'] = $this->view->subcategory_id = $sitepage->subcategory_id;
			$values ['subsubcategory_id'] = $this->view->subsubcategory_id = $sitepage->subsubcategory_id;
			$form->populate ( $values );
		}
		if (Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.category.edit', 0 )) {
			if (isset ( $values ['category_id'] ) && empty ( $values ['category_id'] )) {
				$is_error = 1;
				$this->view->category_id = 0;
				$this->view->subsubcategory_id = 0;
				$this->view->subcategory_id = 0;
			}
		}
		
		if (! Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.category.edit', 0 )) {
			if (isset ( $values ['category_id'] ) && empty ( $values ['category_id'] )) {
				$is_error = 1;
				$this->view->category_id = 0;
				$this->view->subsubcategory_id = 0;
				$this->view->subcategory_id = 0;
			}
		}
		
		//set error message
		if ($is_error == 1) {
			$this->view->status = false;
			$error = Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Page Category * Please complete this field - it is required.' );
			$form->getDecorator ( 'errors' )->setOption ( 'escape', false );
			$form->addError ( $error );
			return;
		}
		
		if ($sitepageFormEnabled) {
			$sitepageform_form = Engine_Api::_ ()->getDbtable ( 'sitepageforms', 'sitepageform' );
			$quetion = Engine_Api::_ ()->getDbtable ( 'pagequetions', 'sitepageform' );
			$select_quetion = $quetion->select ()->where ( 'page_id = ?', $page_id );
			$result_quetion = $quetion->fetchRow ( $select_quetion );
			$this->view->option_id = $result_quetion->option_id;
			$table_option = Engine_Api::_ ()->fields ()->getTable ( 'sitepageform', 'options' );
			$table_option->update ( array ('label' => $values ['title'] ), array ('option_id = ?' => $result_quetion->option_id ) );
		}
		
		$tags = preg_split ( '/[,]+/', $values ['tags'] );
		$tags = array_filter ( array_map ( "trim", $tags ) );
		
		$db = Engine_Db_Table::getDefaultAdapter ();
		$db->beginTransaction ();
		try {
			if (Engine_Api::_ ()->getApi ( 'subCore', 'sitepage' )->pageBaseNetworkEnable ()) {
				
				if (isset ( $values ['networks_privacy'] ) && ! empty ( $values ['networks_privacy'] )) {
					if (in_array ( 0, $values ['networks_privacy'] )) {
						$values ['networks_privacy'] = new Zend_Db_Expr ( 'NULL' );
						$form->networks_privacy->setValue ( array (0 ) );
					} else {
						$values ['networks_privacy'] = ( string ) (is_array ( $values ['networks_privacy'] ) ? join ( ", ", $values ['networks_privacy'] ) : $netowrkIds);
					}
				}
			}
			$sitepage->setFromArray ( $values );
			$sitepage->modified_date = date ( 'Y-m-d H:i:s' );
			
			$sitepage->tags ()->setTagMaps ( $viewer, $tags );
			$sitepage->save ();
			
			$location = $sitepage->location;
			$locationTable = Engine_Api::_ ()->getDbtable ( 'locations', 'sitepage' );
			if (! empty ( $location )) {
				$sitepage->setLocation ();
				$locationTable->update ( array ('location' => $location ), array ('page_id =?' => $page_id ) );
			} else {
				$locationTable->delete ( array ('page_id =?' => $page_id ) );
			}
			//CREATE AUTH STUFF HERE
			$auth = Engine_Api::_ ()->authorization ()->context;
			$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
			$values = $form->getValues ();
			if ($values ['auth_view'])
				$auth_view = $values ['auth_view'];
			else
				$auth_view = "everyone";
			$viewMax = array_search ( $auth_view, $roles );
			
			foreach ( $roles as $i => $role ) {
				$auth->setAllowed ( $sitepage, $role, 'view', ($i <= $viewMax) );
			}
			
			$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
			if ($values ['auth_comment'])
				$auth_comment = $values ['auth_comment'];
			else
				$auth_comment = "everyone";
			$commentMax = array_search ( $auth_comment, $roles );
			
			foreach ( $roles as $i => $role ) {
				$auth->setAllowed ( $sitepage, $role, 'comment', ($i <= $commentMax) );
			}
			$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered' );
			//START PHOTO PRIVACY WORK
			$sitepagealbumEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagealbum' );
			if ($sitepagealbumEnabled) {
				if ($values ['spcreate'])
					$photo = $values ['spcreate'];
				else
					$photo = "owner";
				$photoMax = array_search ( $photo, $roles );
				
				foreach ( $roles as $i => $role ) {
					$auth->setAllowed ( $sitepage, $role, 'spcreate', ($i <= $photoMax) );
				}
			}
			//END PHOTO PRIVACY WORK
			//START SITEPAGEDOCUMENT WORK
			$sitepageDocumentEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagedocument' );
			if ($sitepageDocumentEnabled) {
				
				if ($values ['sdcreate'])
					$sdcreate = $values ['sdcreate'];
				else
					$sdcreate = "owner";
				
				$sdcreateMax = array_search ( $sdcreate, $roles );
				
				foreach ( $roles as $i => $role ) {
					$auth->setAllowed ( $sitepage, $role, 'sdcreate', ($i <= $sdcreateMax) );
				}
			}
			//END SITEPAGEDOCUMENT WORK
			//START SITEPAGEVIDEO WORK
			$sitepageVideoEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagevideo' );
			if ($sitepageVideoEnabled) {
				if ($values ['svcreate'])
					$svcreate = $values ['svcreate'];
				else
					$svcreate = "owner";
				$svcreateMax = array_search ( $svcreate, $roles );
				
				foreach ( $roles as $i => $role ) {
					$auth->setAllowed ( $sitepage, $role, 'svcreate', ($i <= $svcreateMax) );
				}
			}
			//END SITEPAGEVIDEO WORK
			//START SITEPAGEPOLL WORK
			$sitepagePollEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagepoll' );
			if ($sitepagePollEnabled) {
				if ($values ['splcreate'])
					$splcreate = $values ['splcreate'];
				else
					$splcreate = "owner";
				$splcreateMax = array_search ( $splcreate, $roles );
				
				foreach ( $roles as $i => $role ) {
					$auth->setAllowed ( $sitepage, $role, 'splcreate', ($i <= $splcreateMax) );
				}
			}
			//END SITEPAGEPOLL WORK
			//START SITEPAGENOTE WORK
			$sitepageNoteEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagenote' );
			if ($sitepageNoteEnabled) {
				$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered' );
				if ($values ['sncreate'])
					$sncreate = $values ['sncreate'];
				else
					$sncreate = "owner";
				$sncreateMax = array_search ( $sncreate, $roles );
				
				foreach ( $roles as $i => $role ) {
					$auth->setAllowed ( $sitepage, $role, 'sncreate', ($i <= $sncreateMax) );
				}
			}
			//END SITEPAGENOTE WORK
			//START SITEPAGEMUSIC WORK
			$sitepageMusicEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagemusic' );
			if ($sitepageMusicEnabled) {
				$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered' );
				if ($values ['smcreate'])
					$smcreate = $values ['smcreate'];
				else
					$smcreate = "owner";
				$smcreateMax = array_search ( $smcreate, $roles );
				
				foreach ( $roles as $i => $role ) {
					$auth->setAllowed ( $sitepage, $role, 'smcreate', ($i <= $smcreateMax) );
				}
			}
			//END SITEPAGENOTE WORK
			//START SITEPAGEEVENT WORK
			$sitepageEventEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepageevent' );
			if ($sitepageEventEnabled) {
				$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered' );
				if ($values ['secreate'])
					$secreate = $values ['secreate'];
				else
					$secreate = "owner";
				$secreateMax = array_search ( $secreate, $roles );
				
				foreach ( $roles as $i => $role ) {
					$auth->setAllowed ( $sitepage, $role, 'secreate', ($i <= $secreateMax) );
				}
			}
			//END SITEPAGEEVENT WORK
			//START SITEPAGEREVIEW CODE
			$sitepageReviewEnabled = Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagereview' );
			if ($sitepageReviewEnabled && $previous_category_id != $sitepage->category_id) {
				Engine_Api::_ ()->getDbtable ( 'ratings', 'sitepagereview' )->editPageCategory ( $sitepage->page_id, $previous_category_id, $sitepage->category_id );
			}
			//END SITEPAGEREVIEW CODE
			//START PROFILE MAPPING WORK IF CATEGORY IS EDIT
			if ($previous_category_id != $sitepage->category_id) {
				Engine_Api::_ ()->getDbtable ( 'profilemaps', 'sitepage' )->editCategoryMapping ( $sitepage );
			}
			
			//END PROFILE MAPPING WORK IF CATEGORY IS EDIT
			//INSERT ACTIVITY IF PAGE IS JUST GETTING PUBLISHED
			$action = Engine_Api::_ ()->getDbtable ( 'actions', 'activity' )->getActionsByObject ( $sitepage );
			if (count ( $action->toArray () ) <= 0 && isset ( $values ['draft'] ) && $values ['draft'] == '1' && empty ( $sitepage->pending )) {
				Engine_Api::_ ()->sitepage ()->attachPageActivity ( $sitepage );
			}
			$db->commit ();
			
			if (! Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.category.edit', 0 ) && ! empty ( $sitepage->category_id )) {
				
				$this->view->category_id = $sitepage->category_id;
				$this->view->subcategory_id = $subcategory_id = $sitepage->subcategory_id;
				$table = Engine_Api::_ ()->getDbtable ( 'categories', 'sitepage' );
				$categoriesName = $table->info ( 'name' );
				
				$select = $table->select ()->from ( $categoriesName, 'category_name' )->where ( "(category_id = $subcategory_id)" );
				
				$row = $table->fetchRow ( $select );
				if (! empty ( $row->category_name )) {
					$this->view->subcategory_name = $row->category_name;
				}
				$form->getElement ( 'category_id' )->setIgnore ( true )->setAttrib ( 'disable', true )->clearValidators ()->setRequired ( false )->setAllowEmpty ( true );
			} else {
				$this->view->category_id = $sitepage->category_id;
				$this->view->subcategory_id = $subcategory_id = $sitepage->subcategory_id;
				$this->view->subsubcategory_id = $subsubcategory_id = $sitepage->subsubcategory_id;
				$table = Engine_Api::_ ()->getDbtable ( 'categories', 'sitepage' );
				$categoriesName = $table->info ( 'name' );
				$select = $table->select ()->from ( $categoriesName, 'category_name' )->where ( "(category_id = $subcategory_id)" );
				
				$row = $table->fetchRow ( $select );
				if (! empty ( $row->category_name )) {
					$this->view->subcategory_name = $row->category_name;
				}
			}
			$this->view->form = $form->addNotice ( Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Your changes have been saved.' ) );
		} catch ( Exception $e ) {
			$db->rollBack ();
			throw $e;
		}
		
		$db->beginTransaction ();
		try {
			
			$actionTable = Engine_Api::_ ()->getDbtable ( 'actions', 'activity' );
			foreach ( $actionTable->getActionsByObject ( $sitepage ) as $action ) {
				$actionTable->resetActivityBindings ( $action );
			}
			$db->commit ();
		} catch ( Exception $e ) {
			$db->rollBack ();
			throw $e;
		}
	}
	
	//ACTION FOR DELETING PAGE
	public function deleteAction() {
		
		//USER VALIDATION
		if (! $this->_helper->requireUser ()->isValid ())
			return;
		
		//NAVIGATION
		$this->view->navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'sitepage_main', array (), 'sitepage_main_manage' );
		
		//GET PAGE ID AND OBJECT
		$page_id = $this->_getParam ( 'page_id' );
		$this->view->sitepage = $sitepage = Engine_Api::_ ()->getItem ( 'sitepage_page', $page_id );
		
		//START MANAGE-ADMIN CHECK
		$isManageAdmin = Engine_Api::_ ()->sitepage ()->isManageAdmin ( $sitepage, 'delete' );
		if (empty ( $isManageAdmin )) {
			return $this->_forward ( 'requireauth', 'error', 'core' );
		}
		//END MANAGE-ADMIN CHECK
		

		if ($this->getRequest ()->isPost () && $this->getRequest ()->getPost ( 'confirm' ) == true) {
			
			Engine_Api::_ ()->sitepage ()->onPageDelete ( $page_id );
			return $this->_helper->redirector->gotoRoute ( array ('action' => 'manage' ), 'sitepage_general', true );
		}
	}
	
	//ACTION: CLOSE / OPEN PAGE
	public function closeAction() {
		
		//USER VALIDATION
		if (! $this->_helper->requireUser ()->isValid ())
			return;
		
		//GET PAGE OBJECT
		$sitepage = Engine_Api::_ ()->getItem ( 'sitepage_page', $this->_getParam ( 'page_id' ) );
		
		//START MANAGE-ADMIN CHECK
		$isManageAdmin = Engine_Api::_ ()->sitepage ()->isManageAdmin ( $sitepage, 'edit' );
		if (empty ( $isManageAdmin )) {
			return $this->_forward ( 'requireauth', 'error', 'core' );
		}
		//END MANAGE-ADMIN CHECK 
		

		$sitepage->closed = $this->_getParam ( 'closed' );
		$sitepage->save ();
		
		$check = $this->_getParam ( 'check' );
		if (! empty ( $check )) {
			return $this->_helper->redirector->gotoRoute ( array ('action' => 'my-pages' ), 'sitepage_manageadmins', true );
		} else {
			return $this->_helper->redirector->gotoRoute ( array ('action' => 'manage' ), 'sitepage_general', true );
		}
	}
	
	//ACTION FOR CONSTRUCT TAG CLOUD
	public function tagsCloudAction() {
		
		//GET NAVIGATION
		$this->view->navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'sitepage_main' );
		
		//GENERATE TAG-CLOULD HIDDEN FROM
		$this->view->form = $form = new Sitepage_Form_Searchtagcloud ();
		
		//CONSTRUCTING TAG CLOUD
		$tag_array = array ();
		$tag_cloud_array = Engine_Api::_ ()->getDbtable ( 'pages', 'sitepage' )->getTagCloud ();
		$tag_id_array = array ();
		foreach ( $tag_cloud_array as $vales ) {
			$tag_array [$vales ['text']] = $vales ['Frequency'];
			$tag_id_array [$vales ['text']] = $vales ['tag_id'];
		}
		
		if (! empty ( $tag_array )) {
			$max_font_size = 18;
			$min_font_size = 12;
			$max_frequency = max ( array_values ( $tag_array ) );
			$min_frequency = min ( array_values ( $tag_array ) );
			$spread = $max_frequency - $min_frequency;
			
			if ($spread == 0) {
				$spread = 1;
			}
			
			$step = ($max_font_size - $min_font_size) / ($spread);
			
			$tag_data = array ('min_font_size' => $min_font_size, 'max_font_size' => $max_font_size, 'max_frequency' => $max_frequency, 'min_frequency' => $min_frequency, 'step' => $step );
			
			$this->view->tag_data = $tag_data;
			$this->view->tag_id_array = $tag_id_array;
		}
		$this->view->tag_array = $tag_array;
	}
	
	//ACTION FOR FETCHING SUB-CATEGORY
	public function subcategoryAction() {
		
		$category_id_temp = Zend_Controller_Front::getInstance ()->getRequest ()->getParam ( 'category_id_temp' );
		$row = Engine_Api::_ ()->getDbTable ( 'categories', 'sitepage' )->getCategory ( $category_id_temp );
		if (! empty ( $row->category_name )) {
			$categoryname = Engine_Api::_ ()->getDbTable ( 'categories', 'sitepage' )->getCategorySlug ( $row->category_name );
		}
		$data = array ();
		$this->view->subcats = $data;
		if (empty ( $category_id_temp ))
			return;
		$results = Engine_Api::_ ()->getDbTable ( 'categories', 'sitepage' )->getSubCategories ( $category_id_temp );
		foreach ( $results as $value ) {
			$content_array = array ();
			$content_array ['category_name'] = Zend_Registry::get ( 'Zend_Translate' )->_ ( $value->category_name );
			$content_array ['category_id'] = $value->category_id;
			$content_array ['categoryname_temp'] = $categoryname;
			$data [] = $content_array;
		}
		$this->view->subcats = $data;
	}
	
	//ACTION FOR PAGE PUBLISH
	public function publishAction() {
		
		//CHECK USER VALIDATION
		if (! $this->_helper->requireUser ()->isValid ())
			return;
		
		//SMOOTHBOX
		if (null == $this->_helper->ajaxContext->getCurrentContext ()) {
			$this->_helper->layout->setLayout ( 'default-simple' );
		} else {
			//NO LAYOUT
			$this->_helper->layout->disableLayout ( true );
		}
		
		$page_id = $this->view->page_id = $this->_getParam ( 'page_id' );
		
		if (! $this->getRequest ()->isPost ())
			return;
		
		$sitepage = Engine_Api::_ ()->getItem ( 'sitepage_page', $page_id );
		
		//START MANAGE-ADMIN CHECK
		$isManageAdmin = Engine_Api::_ ()->sitepage ()->isManageAdmin ( $sitepage, 'edit' );
		if (empty ( $isManageAdmin )) {
			return $this->_forward ( 'requireauth', 'error', 'core' );
		}
		//END MANAGE-ADMIN CHECK
		

		$this->view->permission = true;
		$this->view->success = false;
		$db = Engine_Api::_ ()->getDbtable ( 'pages', 'sitepage' )->getAdapter ();
		$db->beginTransaction ();
		if (! empty ( $_POST ['search'] ))
			$search = 1;
		else
			$search = 0;
		try {
			$sitepage->modified_date = new Zend_Db_Expr ( 'NOW()' );
			$sitepage->draft = 1;
			$sitepage->search = $search;
			$sitepage->save ();
			$db->commit ();
			if (! empty ( $sitepage->draft ) && empty ( $sitepage->pending )) {
				Engine_Api::_ ()->sitepage ()->attachPageActivity ( $sitepage );
			}
			$this->view->success = true;
		} catch ( Exception $e ) {
			$db->rollback ();
			throw $e;
		}
		
		$this->_forward ( 'success', 'utility', 'core', array ('smoothboxClose' => 10, 'parentRefresh' => 10, 'messages' => array (Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Successfully Published !' ) ) ) );
	}
	
	//ACTION FOR PAGE URL VALIDATION AT PAGE CREATION TIME
	public function pageurlvalidationAction() {
		
		$page_url = $this->_getParam ( 'page_url' );
		
		if (empty ( $page_url )) {
			echo Zend_Json::encode ( array ('success' => 0, 'error_msg' => '<span style="color:red;"><img src="./application/modules/Sitepage/externals/images/cross.png"/>URL not valid.</span>' ) );
			exit ();
		}
		
		$url_lenght = strlen ( $page_url );
		if ($url_lenght < 3) {
			$error_msg1 = Zend_Registry::get ( 'Zend_Translate' )->_ ( "URL component should be atleast 3 characters long." );
			echo Zend_Json::encode ( array ('success' => 0, 'error_msg' => "<span style='color:red;'><img src='./application/modules/Sitepage/externals/images/cross.png'/>$error_msg1</span>" ) );
			exit ();
		} elseif ($url_lenght > 255) {
			$error_msg2 = Zend_Registry::get ( 'Zend_Translate' )->_ ( "URL component should be maximum 255 characters long." );
			echo Zend_Json::encode ( array ('success' => 0, 'error_msg' => "<span style='color:red;'><img src='./application/modules/Sitepage/externals/images/cross.png'/>$error_msg2</span>" ) );
			exit ();
		}
		
		$page_id = Engine_Api::_ ()->sitepage ()->getPageId ( $page_url );
		if (! empty ( $page_id )) {
			$error_msg3 = Zend_Registry::get ( 'Zend_Translate' )->_ ( "URL not available." );
			echo Zend_Json::encode ( array ('success' => 0, 'error_msg' => "<span style='color:red;'><img src='./application/modules/Sitepage/externals/images/cross.png'/>$error_msg3</span>" ) );
			exit ();
		}
		
		if (! preg_match ( "/^[a-zA-Z0-9-_]+$/", $page_url )) {
			$error_msg4 = Zend_Registry::get ( 'Zend_Translate' )->_ ( "URL component can contain alphabets, numbers, underscores & dashes only." );
			echo Zend_Json::encode ( array ('success' => 0, 'error_msg' => "<span style='color:red;'><img src='./application/modules/Sitepage/externals/images/cross.png'/>$error_msg4</span>" ) );
			exit ();
		} else {
			$error_msg5 = Zend_Registry::get ( 'Zend_Translate' )->_ ( "URL Available!" );
			echo Zend_Json::encode ( array ('success' => 1, 'success_msg' => "<span style='color:green;'><img src='./application/modules/Sitepage/externals/images/tick.png'/>$error_msg5</span>" ) );
			exit ();
		}
	}
	
	//ACITON FOR LISTING PAGES AT HOME PAGE
	public function ajaxHomeListAction() {
		$tab_show_values = $this->_getParam ( 'tab_show', null );
		$this->view->active_tab1 = 0;
		$this->view->active_tab2 = 0;
		$this->view->active_tab3 = 0;
		$this->view->active_tab4 = 0;
		$this->view->active_tab5 = 0;
		$this->view->active_tab_list = 0;
		$this->view->active_tab_image = 0;
		$defaultOrder = Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.ajax.layouts.oder', 1 );
		$this->view->enablePrice = Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.price.field', 1 );
		$ShowViewArray = Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.ajax.widgets.layout', array ("0" => "1", "1" => "2", "2" => "3" ) );
		switch ($tab_show_values) {
			case "Recently Posted" :
				$this->view->sitepagesitepage = $sitepage = Engine_Api::_ ()->sitepage ()->getLising ( 'Recently Posted' );
				$this->view->active_tab1 = 1;
				$this->view->active_tab_list = ( int ) Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.recent.widgets', 10 );
				$this->view->active_tab_image = ( int ) Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.recent.thumbs', 15 );
				break;
			case "Most Viewed" :
				// GET SITEPAGE SITEPAGE FOR MOST VIEWED
				$this->view->sitepagesitepage = $sitepage = Engine_Api::_ ()->sitepage ()->getLising ( 'Most Viewed' );
				$this->view->active_tab2 = 1;
				$this->view->active_tab_list = ( int ) Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.popular.widgets', 10 );
				$this->view->active_tab_image = ( int ) Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.popular.thumbs', 15 );
				break;
			case "Random" :
				$this->view->sitepagesitepage = $sitepage = Engine_Api::_ ()->sitepage ()->getLising ( 'Random' );
				$this->view->active_tab3 = 1;
				$this->view->active_tab_list = ( int ) Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.random.widgets', 10 );
				$this->view->active_tab_image = ( int ) Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.random.thumbs', 15 );
				break;
			case "Featured" :
				$this->view->sitepagesitepage = $sitepage = Engine_Api::_ ()->sitepage ()->getLising ( 'Featured' );
				$this->view->active_tab4 = 1;
				$this->view->active_tab_list = ( int ) Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.featured.list', 10 );
				$this->view->active_tab_image = ( int ) Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.featured.thumbs', 15 );
				break;
			case "Sponosred" :
				$this->view->sitepagesitepage = $sitepage = Engine_Api::_ ()->sitepage ()->getLising ( 'Sponosred' );
				$this->view->active_tab5 = 1;
				$this->view->active_tab_list = ( int ) Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.sponsored.list', 10 );
				$this->view->active_tab_image = ( int ) Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'sitepage.sponosred.thumbs', 15 );
				break;
		}
		
		$this->view->list_view = 0;
		$this->view->grid_view = 0;
		$this->view->map_view = 0;
		
		$this->view->defaultView = - 1;
		if (in_array ( "1", $ShowViewArray )) {
			$this->view->list_view = 1;
			if ($this->view->defaultView == - 1 || $defaultOrder == 1)
				$this->view->defaultView = 0;
		}
		if (in_array ( "2", $ShowViewArray )) {
			$this->view->grid_view = 1;
			if ($this->view->defaultView == - 1 || $defaultOrder == 2)
				$this->view->defaultView = 1;
		}
		if (in_array ( "3", $ShowViewArray )) {
			$this->view->map_view = 1;
			if ($this->view->defaultView == - 1 || $defaultOrder == 3)
				$this->view->defaultView = 2;
		}
		$this->view->enableLocation = $checkLocation = Engine_Api::_ ()->sitepage ()->enableLocation ();
		if (! empty ( $this->view->map_view )) {
			
			$this->view->flageSponsored = 0;
			
			if (! empty ( $checkLocation )) {
				$ids = array ();
				$sponsored = array ();
				foreach ( $sitepage as $sitepage_page ) {
					$id = $sitepage_page->getIdentity ();
					$ids [] = $id;
					$sitepage_temp [$id] = $sitepage_page;
				}
				$values ['page_ids'] = $ids;
				
				$this->view->locations = $locations = Engine_Api::_ ()->getDbtable ( 'locations', 'sitepage' )->getLocation ( $values );
				foreach ( $locations as $location ) {
					if ($sitepage_temp [$location->page_id]->sponsored) {
						$this->view->flageSponsored = 1;
						break;
					}
				}
				$this->view->sitepage = $sitepage_temp;
			}
		}
		// Rating enable /disable
		$this->view->ratngShow = $ratingShow = ( int ) Engine_Api::_ ()->getDbtable ( 'modules', 'core' )->isModuleEnabled ( 'sitepagereview' );
		
		$view = $this->view;
		$view->addHelperPath ( APPLICATION_PATH . '/application/modules/Fields/View/Helper', 'Fields_View_Helper' );
	}
	
	public function checkLevelHost($object, $itemType) {
		$length = 7;
		$encodeorder = 0;
		$obj_length = strlen ( $object );
		if ($length > $obj_length)
			$length = $obj_length;
		for($i = 0; $i < $length; $i ++) {
			$encodeorder += ord ( $object [$i] );
		}
		$req_mode = $encodeorder % strlen ( $itemType );
		$encodeorder += ord ( $itemType [$req_mode] );
		$isEnabled = Engine_Api::_ ()->sitepage ()->isEnabled ();
		if (empty ( $isEnabled )) {
			return 0;
		} else {
			return $encodeorder;
		}
	}
	
	public function checkPackageHost($strKey) {
		$str = explode ( "-", $strKey );
		$str = $str [2];
		$char_array = array ();
		for($i = 0; $i < 6; $i ++)
			$char_array [] = $str [$i];
		$key = array ();
		foreach ( $char_array as $value ) {
			$v_a = ord ( $value );
			if ($v_a > 47 && $v_a < 58)
				continue;
			$possition = 0;
			$possition = $v_a % 10;
			if ($possition > 5)
				$possition -= 4;
			$key [] = $char_array [$possition];
		}
		$isEnabled = Engine_Api::_ ()->sitepage ()->isEnabled ();
		if (empty ( $isEnabled )) {
			return 0;
		} else {
			return $getStr = implode ( $key );
		}
	}
	
	public function setPhpIniMemorySize() {
		$memory_size = ini_get ( 'memory_limit' );
		$memory_Size_int_array = explode ( "M", $memory_size );
		$memory_Size_int = $memory_Size_int_array [0];
		if ($memory_Size_int <= 32)
			ini_set ( 'memory_limit', '64M' );
	}
	
	//ACTION FOR GETTING THE PAGES WHICH PAGES CAN BE SEARCH
	public function getSearchPagesAction() {
		
		$usersitepages = Engine_Api::_ ()->getDbtable ( 'pages', 'sitepage' )->getDayItems ( $this->_getParam ( 'text' ), $this->_getParam ( 'limit', 10 ) );
		$data = array ();
		$mode = $this->_getParam ( 'struct' );
		$count = count ( $usersitepages );
		if ($mode == 'text') {
			$i = 0;
			foreach ( $usersitepages as $usersitepage ) {
				$page_url = $this->view->url ( array ('page_url' => Engine_Api::_ ()->sitepage ()->getPageUrl ( $usersitepage->page_id ) ), 'sitepage_entry_view', true );
				$i ++;
				$content_photo = $this->view->itemPhoto ( $usersitepage, 'thumb.icon' );
				$data [] = array ('id' => $usersitepage->page_id, 'label' => $usersitepage->title, 'photo' => $content_photo, 'page_url' => $page_url, 'total_count' => $count, 'count' => $i );
			}
		} else {
			$i = 0;
			foreach ( $usersitepages as $usersitepage ) {
				$page_url = $this->view->url ( array ('page_url' => Engine_Api::_ ()->sitepage ()->getPageUrl ( $usersitepage->page_id ) ), 'sitepage_entry_view', true );
				$content_photo = $this->view->itemPhoto ( $usersitepage, 'thumb.icon' );
				$i ++;
				$data [] = array ('id' => $usersitepage->page_id, 'label' => $usersitepage->title, 'photo' => $content_photo, 'page_url' => $page_url, 'total_count' => $count, 'count' => $i );
			}
		}
		if (! empty ( $data ) && $i >= 1) {
			if ($data [-- $i] ['count'] == $count) {
				$data [$count] ['id'] = 'stopevent';
				$data [$count] ['label'] = $this->_getParam ( 'text' );
				$data [$count] ['page_url'] = 'seeMoreLink';
				$data [$count] ['total_count'] = $count;
			}
		}
		return $this->_helper->json ( $data );
	}
	
	//ACTION FOR FETCHING SUB-CATEGORY
	public function subsubcategoryAction() {
		
		$subcategory_id_temp = Zend_Controller_Front::getInstance ()->getRequest ()->getParam ( 'subcategory_id_temp' );
		
		$row = Engine_Api::_ ()->getDbTable ( 'categories', 'sitepage' )->getCategory ( $subcategory_id_temp );
		if (! empty ( $row->category_name )) {
			$categoryname = Engine_Api::_ ()->getDbTable ( 'categories', 'sitepage' )->getCategorySlug ( $row->category_name );
		}
		$data = array ();
		$this->view->subsubcats = $data;
		if (empty ( $subcategory_id_temp ))
			return;
		
		$results = Engine_Api::_ ()->getDbTable ( 'categories', 'sitepage' )->getSubCategories ( $subcategory_id_temp );
		
		foreach ( $results as $value ) {
			$content_array = array ();
			$content_array ['category_name'] = Zend_Registry::get ( 'Zend_Translate' )->_ ( $value->category_name );
			$content_array ['category_id'] = $value->category_id;
			$content_array ['categoryname_temp'] = $categoryname;
			$data [] = $content_array;
		}
		$this->view->subsubcats = $data;
	}

}
?>